<?php

declare(strict_types=1);

namespace app\admin\controller;

use think\facade\View; //模板引擎
use app\common\Base;
use think\facade\Request;
use think\exception\ValidateException;
use app\validate\UsersVal;
use app\model\Users as UsersMod;

/**
 * @name 用户管理
 */
class Users extends Base
{
    /**
     * @name 用户列表
     */
    public function list()
    {
        $list =  UsersMod::list('', 1, 10);
        View::assign('count', $list['count']);
        if (request()->isPost()) {
            $param = Request::param();
            $list =  UsersMod::list('', (int)$param['curr'], (int)$param['limit']);
            return getBack(0, '', $list);
        }
        return View::fetch();
    }

    /**
     * @name 用户添加
     */
    public function add()
    {
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(UsersVal::class)->scene('add')->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $find = UsersMod::where([['mobile', '=', $param['mobile']]]);
            if ($find) {
                return getBack(1, ['name' => 'mobile', 'msg' => '该手机号已被注册']);
            }
            $param['password'] = $this->md5_salt($param['password']);
            $res = UsersMod::add($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }

    /**
     * @name 用户编辑
     */
    public function edit()
    {
        if (request()->isGet()) {
            $id = Request::param('id');
            $find = UsersMod::where([['id', '=', $id]]);
            View::assign('find', $find);
        }
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(UsersVal::class)->scene('edit')->check($param);
            } catch (ValidateException $e) {
                return getBack(1, $e->getError());
            }
            $find = UsersMod::where([['mobile', '=', $param['mobile']], ['id', 'not in', $param['id']]]);
            if ($find) {
                return getBack(1, ['name' => 'mobile', 'msg' => '该手机号已被注册']);
            }
            if ($param['updatepwd'] != '' && $param['updatepwd'] != null) {
                $param['password'] = $this->md5_salt($param['updatepwd']);
            } else {
                unset($param['password']);
            }
            unset($param['updatepwd']);
            $res = UsersMod::edit($param);
            if ($res) {
                return getBack(0);
            } else {
                return getBack(2);
            }
        }
        return View::fetch();
    }
}
